// pages/mails/searchAddress/searchAddress.js
Page({

      /**
       * 页面的初始数据
       */
      data: {
            ajaxData: [{
                  id: 'wx_zhangsansan_23563224',
                  name: '张珊珊',
                  phone: '17456765234',
                  address: `上海大毛中西来得及佛尔基督教欧风了实地解放空当接龙费劲儿偶发`
            }], // 请求得到的数据
            addressData: [], // 在页面中展示数据
            meiyoushuju: true, // 控制没有数据时，要显示的元素
            searchValue: '', // 存储搜索框的值
            cancel: true, // 搜索框中的清空按钮
      },

      /**
       * 生命周期函数--监听页面加载
       */
      onLoad: function (options) {
            this.init_()
      },
      // 页面初始化
      init_() {
            let app = getApp().globalData;
            let addressBook = app['addressBook'];
            if (addressBook && addressBook.length == 0) {
                  this.setData({
                        ajaxData: []
                  })
            } else {
                  let addressBook_ = JSON.parse(JSON.stringify(addressBook))
                  addressBook_.forEach(element => {
                        // console.log(element)
                        element['address'] = setDetailAddress(element)
                        element['phone'] = element['phone'] + ''
                  });
                  // console.log(addressBook_)
                  this.setData({
                        ajaxData: addressBook_
                  })

                  function setDetailAddress(data) {
                        // console.log(data)
                        return data['address_components'].city + data['address_components'].district + data['address_components'].province + data['address_components'].street + data['address_components'].street_number + '(' + data.title + ' ' + data['address_components'].company + ')';
                  }
            }

            this.setData({
                  addressData: JSON.parse(JSON.stringify(this.data.ajaxData))
            })
            if (this.data.addressData.length === 0) {
                  this.setData({
                        meiyoushuju: false
                  })
            }
      },
      // 搜索操作--高亮
      searchInput(event) {
            // console.log(event.detail)
            let value = event.detail.value;
            // console.log(typeof value)
            let addressData_ = [];
            for (let index = 0; index < this.data.ajaxData.length; index++) {
                  let data = Object.assign({}, this.data.ajaxData[index]);
                  let searchText_;
                  if (/^\d*$/g.test(value)) { // 如果是数字
                        searchText_ = this.searchText(data.phone, value, 'color4')
                        data.phone !== searchText_ ? (data['phone'] = searchText_, addressData_.push(data)) : ''
                  } else {
                        let flag = false
                        searchText_ = this.searchText(data.name, value, 'color4')
                        data.name !== searchText_ ? (data['name'] = searchText_, flag = true) : ''
                        let searchText_2 = this.searchText(data.address, value, 'color4')
                        data.address !== searchText_2 ? (data['address'] = searchText_2, flag = true) : ''
                        flag && (data.name === searchText_ || data.address === searchText_2) ? addressData_.push(data) : ''
                  }
            }
            this.setData({
                  searchValue: value,
                  addressData: addressData_,
                  cancel: value ? false : true
            })
      },

      /**
       * 高亮拼接显示要搜索的文本
       * @text 被匹配的文本
       * @value 要匹配并高亮的值
       * @classname 高亮文本的样式
       */
      searchText(text, value, classname) {
            try {
                  let text_ = JSON.parse(JSON.stringify(text))
                  return text_.replace(value, `<span class="${classname}">${value}</span>`);
            } catch (e) {
                  return text;
            }
      },
      // 清空搜索内容
      resetSearch() {
            this.setData({
                  searchValue: '',
                  addressData: this.data.ajaxData,
                  cancel: true
            })
      },
      // 更改默认地址时触发
      radioGroup(e) {
            let detail = e.detail;
            // console.log(e)
            // console.log(detail.value)
            wx.showToast({
                  title: '默认地址更改成功',
                  icon: 'none',
                  duration: 1000
            })
      },
      /* 删除选中的地址 */
      deleteAddress(e) {
            console.log(e.currentTarget.dataset['id'])
            wx.showModal({
                  content: '确认要删除该地址吗？',
                  showCancel: true,
                  cancelColor: '#8A8A8A',
                  confirmColor: '#E76976',
                  success(res) {
                        if (res.confirm) {
                              wx.showToast({
                                    title: '删除成功',
                                    icon: 'none',
                                    duration: 1000
                              })
                        } else if (res.cancel) {
                              console.log('用户点击取消')
                        }
                  }
            })
      },
      // 选中对应的地址数据，并返上一页去
      backAddressData(e) {
            let id = e.currentTarget.dataset['id'];
            let addressBook = getApp().globalData['addressBook'];
            var data = null
            // console.log(id)
            for (let index = 0; index < addressBook.length; index++) {
                  if (addressBook[index]['id'] === id) {
                        data = addressBook[index]
                        break;
                  }
            }
            const eventChannel = this.getOpenerEventChannel()
            // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
            let type = ''
            eventChannel.on('acceptDataFromOpenerPage', function (data) {
                  // console.log(data)
                  type = data.type
            })
            // 把值传给打开该页面的页面
            eventChannel.emit('acceptDataFromOpenedPage', {
                  "data": data,
                  "type": type
            });
            wx.navigateBack({
                  delta: 1,
            })
      },
      // 跳转到新的页面
      detailAddr(e) {
            let address = e.currentTarget.dataset.addr;
            if (!address) return;
            console.log(address)
            wx.navigateTo({
                  url: address
            })
      },

})